# -*- coding:UTF-8 -*-

import hashlib
from pypinyin import lazy_pinyin
import time
import datetime
import random
import re
import xmltodict

__doc__ = """
    工具类
"""

__author__ = 'akin, Jone Wang, '

"""
 * 加密字符串SHA加密
 *
 * @param txt
 * @return
"""


def encrypt(text):
    """
    :param text:
    :return:
    """
    hash_it = hashlib.sha1()
    hash_it.update(text)
    return hash_it.hexdigest()


"""
  * 中文转拼音
"""


def word_to_pinyin(txt):
    pinyin_set = lazy_pinyin(txt)

    pinyin_str = ""
    for code in pinyin_set:
        pinyin_str += code

    return pinyin_str


"""
  * 生成批次号
"""


def create_batch():
    return now_format_no() + random_num(5)


"""
  * 获取当前时间yyyy-MM-dd hh:mm:ss
"""


def now():
    now = int(time.time())
    timeArray = time.localtime(now)

    print(int(time.strftime("%d", timeArray)))

    return time.strftime("%Y-%m-%d %H:%M:%S", timeArray)


"""
  * 获取当前时间,并格式化为yyyyMMddhhmmss
"""


def now_format_no():
    now = int(time.time())
    timeArray = time.localtime(now)

    print(int(time.strftime("%d", timeArray)))

    return time.strftime("%Y%m%d%H%M%S", timeArray)


def timestamp():
    now = int(time.time())
    return now


def month_day():
    now = int(time.time())
    timeArray = time.localtime(now)

    return int(time.strftime("%d", timeArray))


"""
  * 格式化时间 yyyy-MM-dd hh:mm:ss
"""


def format_datetime(dt):
    try:
        if dt is not None:
            return dt.strftime("%Y-%m-%d %H:%M:%S")
        else:
            return ""
    except:
        return " "


"""
  * 格式化时间 yyyy-MM-dd
"""


def format_short_date(dt):
    try:
        if dt is not None:
            return dt.strftime("%Y-%m-%d")
        else:
            return ""
    except:
        return " "


"""
  * 格式化时间 yyyy-MM-dd hh:mm
"""


def format_datetime_nos(dt):
    try:
        if dt is not None:
            return dt.strftime("%Y-%m-%d %H:%M")
        else:
            return ""
    except:
        return " "


"""
  * 将字符串转成date类型 格式 yyyy-MM-dd
"""


def change_str_2_date(date_str):
    dt = time.strptime(date_str, "%Y-%m-%d")
    dt = datetime.datetime(*dt[:3])
    return dt


"""
    * 根据输入的时间计算是星期几
"""


def days_of_week(dtime):
    days = dtime.strftime("%w")

    daysweek = ''

    if days == '1':
        daysweek = u'周一'
    elif days == '2':
        daysweek = u'周二'
    elif days == '3':
        daysweek = u'周三'
    elif days == '4':
        daysweek = u'周四'
    elif days == '5':
        daysweek = u'周五'
    elif days == '6':
        daysweek = u'周六'
    elif days == '0':
        daysweek = u'周日'

    return daysweek


def days_of_week1(dtime):
    """
    返回星期几
    :param dtime:
    :return:
    """
    days = dtime.strftime("%w")

    daysweek = ''

    if days == '1':
        daysweek = u'星期一'
    elif days == '2':
        daysweek = u'星期二'
    elif days == '3':
        daysweek = u'星期三'
    elif days == '4':
        daysweek = u'星期四'
    elif days == '5':
        daysweek = u'星期五'
    elif days == '6':
        daysweek = u'星期六'
    elif days == '0':
        daysweek = u'星期日'

    return daysweek


# 把小时转换成 小时：分钟 格式
def format_hour(hours):
    hh = int(hours)

    m = hours - hh

    mm = int(m * 60)

    return str(hh) + ":" + str(mm)

    return ''


def compare_time(str_t1, str_t2):
    """
    比较两个时间字符串的大小
    :param str_t1:
    :param str_t2: 被比时间
    :return: 1 大于, 0 相等, -1 小于
    """
    compare_time_long = time.mktime(time.strptime(str_t1, '%Y-%m-%d %H:%M:%S'))
    compared_time_logn = time.mktime(time.strptime(str_t2, '%Y-%m-%d %H:%M:%S'))
    result = float(compare_time_long) - float(compared_time_logn)
    if result > 0:
        return 1
    elif result < 0:
        return -1
    return 0


def escape(text):
    return text.replace('&', '&amp;').replace('<', '&lt;').replace('>', '&gt;').replace('"', '&quot;').replace('\'',
                                                                                                               '&#x27;')


def calculateRouteSportTime(times):
    c = 0.0
    for i, v in enumerate(times):
        if i > 0:
            # 第一个点
            t1 = datetime.datetime.strptime(times[i - 1]["time"], '%Y-%m-%d %H:%M:%S')
            # 第二个点
            t2 = datetime.datetime.strptime(times[i]["time"], '%Y-%m-%d %H:%M:%S')
            if t1 and t2:
                d = (t2 - t1).seconds
                c = c + d
    return c / 3600


class Page(object):
    def __init__(self, item_count, page_index=1, page_size=15):

        self.item_count = item_count
        self.page_size = page_size
        self.page_count = item_count // page_size + (1 if item_count % page_size > 0 else 0)
        if (item_count == 0) or (page_index < 1) or (page_index > self.page_count):
            self.offset = 0
            self.limit = 0
            self.page_index = 1
        else:
            self.page_index = page_index
            self.offset = self.page_size * (page_index - 1)
            self.limit = self.page_size
        self.has_next = self.page_index < self.page_count
        self.has_previous = self.page_index > 1
        after_range_num = 4
        befor_range_num = 5
        self.page_range = []
        end_page = page_index + befor_range_num
        if end_page >= self.page_count:
            end_page = self.page_count + 1

        if page_index > after_range_num:
            page_range = [i for i in range(page_index - after_range_num, end_page)]
        else:
            page_range = [i for i in range(1, end_page)]
        self.page_range = page_range

    def __str__(self):
        return 'item_count: %s, page_count: %s, page_index: %s, page_size: %s, offset: %s, limit: %s' % (
            self.item_count, self.page_count, self.page_index, self.page_size, self.offset, self.limit)

    __repr__ = __str__


chmap = {
    '0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9,
    'x': 10, 'X': 10}


def verify_idno(s):
    """
    验证身份证号码是否合格
    :param s:
    :return:
    """
    char_list = list(s)
    num_list = [chmap[ch] for ch in char_list]

    summ = 0
    for ii, n in enumerate(num_list):
        i = 18 - ii
        weight = 2 ** (i - 1) % 11
        summ = (summ + n * weight) % 11
    return summ == 1


def check_id_no(idcard):
    """
    校验身份证
    :param: idcard
    :rtype: object
    """
    errors = ['验证通过!', '身份证号码位数不对!', '身份证号码出生日期超出范围或含有非法字符!', '身份证号码校验错误!', '身份证地区非法!']
    area = {"11": "北京", "12": "天津", "13": "河北", "14": "山西", "15": "内蒙古", "21": "辽宁", "22": "吉林", "23": "黑龙江", "31": "上海"
        , "32": "江苏", "33": "浙江", "34": "安徽", "35": "福建", "36": "江西", "37": "山东", "41": "河南", "42": "湖北", "43": "湖南"
        , "44": "广东", "45": "广西", "46": "海南", "50": "重庆", "51": "四川", "52": "贵州", "53": "云南", "54": "西藏", "61": "陕西"
        , "62": "甘肃", "63": "青海", "64": "宁夏", "65": "新疆", "71": "台湾", "81": "香港", "82": "澳门", "91": "国外"}
    idcard = str(idcard)
    idcard = idcard.strip()
    idcard_list = list(idcard)

    if (not area[(idcard)[0:2]]):
        return False, errors[4]

    if (len(idcard) == 15):
        if ((int(idcard[6:8]) + 1900) % 4 == 0 or (
                (int(idcard[6:8]) + 1900) % 100 == 0 and (int(idcard[6:8]) + 1900) % 4 == 0)):
            erg = re.compile(
                '[1-9][0-9]{5}[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|[1-2][0-9]))[0-9]{3}$')
        else:
            ereg = re.compile(
                '[1-9][0-9]{5}[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|1[0-9]|2[0-8]))[0-9]{3}$')
        if (re.match(ereg, idcard)):
            return True
        else:
            return False, errors[2]
    elif (len(idcard) == 18):
        if (int(idcard[6:10]) % 4 == 0 or (int(idcard[6:10]) % 100 == 0 and int(idcard[6:10]) % 4 == 0)):
            ereg = re.compile(
                '[1-9][0-9]{5}19[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|[1-2][0-9]))[0-9]{3}[0-9Xx]$')
        else:
            ereg = re.compile(
                '[1-9][0-9]{5}19[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|1[0-9]|2[0-8]))[0-9]{3}[0-9Xx]$')
        if (re.match(ereg, idcard)):
            S = (int(idcard_list[0]) + int(idcard_list[10])) * 7 + (int(idcard_list[1]) + int(idcard_list[11])) * 9 + (
                    int(
                        idcard_list[
                            2]) + int(
                idcard_list[
                    12])) * 10 + (
                        int(
                            idcard_list[
                                3]) + int(
                    idcard_list[
                        13])) * 5 + (
                        int(
                            idcard_list[
                                4]) + int(
                    idcard_list[
                        14])) * 8 + (
                        int(
                            idcard_list[
                                5]) + int(
                    idcard_list[
                        15])) * 4 + (
                        int(
                            idcard_list[
                                6]) + int(
                    idcard_list[
                        16])) * 2 + int(
                idcard_list[7]) * 1 + int(idcard_list[8]) * 6 + int(idcard_list[9]) * 3
            Y = S % 11
            M = "F"
            JYM = "10X98765432"
            M = JYM[Y]
            if (M == idcard_list[17]):
                return True
            else:
                return False, errors[3]
        else:
            return False, errors[2]
    else:
        return False, errors[1]


def get_birthday_from_idno(idno):
    """
    从身份证号码中获取生日 yyyy-MM-dd格式
    :param idno:
    :return:
    """
    birth_part = idno[6:14]
    return birth_part[:4] + "-" + birth_part[4:6] + "-" + birth_part[6:]


def get_gender_from_idno(idno):
    """
    获得性别
    :param idno:
    :return:
    """
    try:
        gender = 2
        if len(idno) == 15:
            gender = int(idno[14]) % 2
        elif len(idno) == 18:
            gender = int(idno[16]) % 2
        if gender < 2:
            if gender == 1:
                return '1'
            else:
                return '0'
        return '2'
    except Exception as e:
        return '2'


def verify_phoneno(phoneno):
    """
    验证手机号码是否合格
    :param phoneno:
    :return:
    """
    if len(phoneno) == 11:
        if phoneno[0] == '1':
            return True

    return False


def random_chars(size):
    return ''.join(random.sample("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890", size))


def random_num(size):
    return ''.join(random.sample("1234567890", size))


def get_patch_params(obj, index, par):
    """
    设置model参数格式
    :param obj:
    :param index:
    :param par:
    """
    index = str(index)
    for k, v in obj.items():
        par[index + k] = v


def ifNoneParseNullString(data, left):
    """
    如果为空则返回''如果不为空可在前面添加自定义字符串
    :param data:
    :param left:
    """
    if data:
        if data == 'None':
            return ""
        return left + data
    else:
        return ""


def trans_xml_to_dict(xml):
    """
    将返回的 XML 格式数据转化为 Python Dict 对象

    :param xml: 原始 XML 格式数据
    :return: dict 对象
    """

    data = xmltodict.parse(xml)

    return data


def trans_dict_to_xml(data):
    """
    将 dict 对象转换成微信支付交互所需的 XML 格式数据

    :param data: dict 对象
    :return: xml 格式数据
    """

    xml = []
    for k in sorted(data.keys()):
        v = data.get(k)
        if k == 'detail' and not v.startswith('<![CDATA['):
            v = '<![CDATA[{}]]>'.format(v)
        xml.append('<{key}>{value}</{key}>'.format(key=k, value=v))
    # return '<xml>{}</xml>'.format(''.join(xml))
    return ''.join(xml)


if __name__ == "__main__":
    str = '2016050921001004140252464353^0.01^SUCCESS'
    ss = str.split('^')
    print(ss)
